import meals from '@/assets/json/drinks.json';
<template>
  <div>
    <el-row
      v-for="(row, rowIndex) in rows"
      :key="'row-' + rowIndex"
      class="meal-row"
    >
      <el-col
        :span="6"
        v-for="meal in row"
        :key="'meal-' + meal.id"
        class="meal-col"
      >
        <div class="grid-content bg-purple">
          <el-card :body-style="{ padding: '30px' }" shadow="hover">
            <img :src="meal.src" class="image" />
            <div style="padding: 14px">
              <span>{{ meal.name }}</span>
              <div class="bottom clearfix">
                <time class="time price">{{ meal.price }} 元/份</time>
                <el-divider></el-divider>
                <el-button type="text" class="button" @click="selectMeal(meal)"
                  ><i class="el-icon-plus"></i>点我选择</el-button
                >
              </div>
            </div>
          </el-card>
          <el-dialog :visible.sync="dialogVisible">
            <!-- 显示可选配料 -->
            <div v-if="selectedMeal">
              <div
                v-for="(optionsGroup, groupType) in selectedMeal.options"
                :key="groupType"
              >
                <h4>{{ groupType }}</h4>
                <el-checkbox-group v-model="selectedOptions[groupType]">
                  <el-checkbox
                    v-for="option in optionsGroup"
                    :key="option"
                    :label="option"
                    >{{ option }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
            </div>
            <!-- 显示烹饪方法 -->
            <div v-if="selectedMeal && selectedMeal.cookingMethods">
              <label>烹饪方法:</label>
              <el-radio-group v-model="selectedCookingMethod">
                <el-radio
                  v-for="method in selectedMeal.cookingMethods"
                  :label="method"
                  :key="method"
                  >{{ method }}</el-radio
                >
              </el-radio-group>
            </div>
            <br />
            <br />
            <!-- 增加和删减餐品 -->
            <div class="meal-quantity">
              <label for="mealCount">数量:</label>
              <i class="el-icon-minus" @click="decreaseCount"></i>
              <span id="mealCount">{{ selectedMealCount }}</span>
              <!-- 显示数量 -->
              <i class="el-icon-plus" @click="increaseCount"></i>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="open">立即购买</el-button>
              <el-button type="primary" @click="confirmSelection"
                >加入购物车</el-button
              >
            </span>
          </el-dialog>
        </div></el-col
      >
    </el-row>
  </div>
</template>
<style>
.meal-quantity i {
  cursor: pointer; /* 鼠标悬停时显示指针手势 */
  margin-left: 10px; /* 左边距 */
  margin-right: 10px; /* 右边距 */
}
</style>
<script>
import axios from 'axios';
const mealsUrl = "/assets/json/drinks.json";
export default {
  data() {
    return {
      currentDate: new Date().toLocaleDateString(),
      meals: [],
      selectedMeal: {},
      dialogVisible: false,
      selectedOptions: {},
      selectedCookingMethod: "",
      selectedMealCount: 1,
    };
  },
  created() {
    fetch(mealsUrl)
      .then((response) => response.json())
      .then((data) => {
        this.meals = data.drinks;
      })
      .catch((error) => {
        console.error("Error fetching meals:", error);
      });
  },
  computed: {
    // 计算应该渲染多少行，每行 4 个卡片
    rows() {
      return this.meals.reduce((rows, meal, index) => {
        if (index % 4 === 0) {
          rows.push([]);
        }
        rows[rows.length - 1].push(meal);
        return rows;
      }, []);
    },
  },
  methods: {
    // handleClose(done) {
    //     this.$confirm('确认关闭？')
    //       .then(_ => {
    //         done();
    //       })
    //       .catch(_ => {});
    //   }
    //
    selectMeal(meal) {
      this.selectedOptions = { ...meal.options }; // 初始化选项
      this.selectedMeal = meal;
      this.dialogVisible = true; // 打开弹出框
      this.selectedCookingMethod = meal.cookingMethods
        ? meal.cookingMethods[0]
        : ""; // 如果有烹饪方法，则设置第一个方法为默认
    },
    confirmSelection() {
      this.addToCart(this.selectedMeal);
      this.dialogVisible = false;
      console.log("购物车内容:", this.$store.state.cart);
    },
     buyImmediately(){
       const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
      const day = currentDate.getDate().toString().padStart(2, '0');
      const hour = currentDate.getHours().toString().padStart(2, '0');
      const minute = currentDate.getMinutes().toString().padStart(2, '0');
      const second = currentDate.getSeconds().toString().padStart(2, '0');
      const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      let record = {
        userId: this.$route.query.loginUserId,
        names: this.selectedMeal.name,
        prices: this.selectedMeal.price,
        date: formattedDate
      };
      axios.post("http://localhost:8080/payNow",record).then((result)=>{
        console.log(result.data)
      }).catch(()=>{
        console.log("error")
      })
      console.log(record)
    },
    open() {
        this.$alert('确定购买吗？', '温馨提示', {
          confirmButtonText: '是',
          callback: action => {
            this.$message({
              type: 'info',
              message: '谢谢惠顾'
            });
            if (action==='confirm')
            {
               this.buyImmediately();
               //  购买完关闭弹出框
               this.dialogVisible=false
            }
           
          }
        });
      },
    // 增加和删除商品的数量
    increaseCount() {
      if (this.selectedMealCount < 100) {
        // 假设最多只能选择100份
        this.selectedMealCount += 1;
      }
    },
    decreaseCount() {
      if (this.selectedMealCount > 1) {
        this.selectedMealCount -= 1;
      }
    },
    addToCart(meal) {
      // 创建一个新的对象，包含meal对象的属性以及用户选择的烹饪方式和配料
      const cartItem = {
        ...meal,
        quantity: this.selectedMealCount,
        selectedCookingMethod: this.selectedCookingMethod,
        selectedOptions: this.selectedOptions,
      };

      // 派发action到Vuex store
      this.$store.dispatch("addToCart", cartItem);
    },
  },
};
</script>